package com.xxx.service.task;

import com.xxx.dao.TaskMonitorConfigMapper;
import com.xxx.dao.TaskMonitorRecordMapper;
import com.xxx.domain.TaskMonitorConfig;
import com.xxx.domain.TaskMonitorConfigExample;
import com.xxx.domain.TaskMonitorRecord;
import com.xxx.domain.TaskMonitorRecordExample;
import com.xxx.utils.Constants;
import com.xxx.utils.Constants.Dvp;
import com.xxx.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * desc:定时任务监控定时发送告警邮件服务
 *
 * @author wangchengwang
 * @date 2018/10/17
 */
@Component
public class TaskMonitorTaskService {

    @Autowired
    private TaskMonitorRecordMapper TaskMonitorRecordMapper;

    @Autowired
    private TaskMonitorConfigMapper TaskMonitorConfigMapper;

    @Autowired
    private RedisOperatorJedisCluster redisOperatorJedisCluster;

    @Autowired
    private EmailService emailService;

    private static final Logger LOG = LoggerFactory.getLogger(TaskMonitorTaskService.class);

    private static StringBuffer taskMonitorPage = new StringBuffer();

    private final Long FIVEHOUR = 18000000L;

    private static String[] heads = new String[]{"任务名称", "ip地址", "商户编号", "告警信息", "开始时间", "异常时间", "完成时间"};


    /**
     * 定时任务监控告警服务
     */
    public void sendTaskMonitorInfo() {
        try {
            LOG.info("TaskMonitorTaskService.sendTaskMonitorInfo start time={}", TimeUtils.getFormateTimeNotNull(new Date(), "yyyy-MM-dd HH:mm:ss"));
            String title = "定时任务监控告警";
            TaskMonitorConfigExample TaskMonitorConfigExample = new TaskMonitorConfigExample();
            TaskMonitorConfigExample.Criteria configCriteria = TaskMonitorConfigExample.createCriteria();
            TaskMonitorRecordExample TaskMonitorRecordExample = new TaskMonitorRecordExample();
            TaskMonitorRecordExample.Criteria recordCriteria = TaskMonitorRecordExample.createCriteria();
            Long date = System.currentTimeMillis();
            recordCriteria.andGmtCreateBetween(TimeUtils.getNowDayTime(date), date);

            List<TaskMonitorConfig> TaskMonitorConfigs = TaskMonitorConfigMapper.selectByExample(TaskMonitorConfigExample);
            for (TaskMonitorConfig TaskMonitorConfig : TaskMonitorConfigs) {
                taskMonitorPage.setLength(0);
                String[] taskNames = TaskMonitorConfig.getTaskName().split("[;；,，]");
                List<String> taskNameList = new ArrayList<>(Arrays.asList(taskNames));
                recordCriteria.andTaskNameIn(taskNameList);
                List<TaskMonitorRecord> TaskMonitorRecordList = TaskMonitorRecordMapper.selectByExample(TaskMonitorRecordExample);
                if (TaskMonitorRecordList == null || TaskMonitorRecordList.size() == 0) {
                    continue;
                }
                taskMonitorEmailPage(TaskMonitorRecordList, taskNameList);
                if (taskMonitorPage.length() != 0) {
                    //使用邮件服务，发送邮件
                    emailService.send(EmailService.Sender.system, TaskMonitorConfig.getTaskUser(), title, taskMonitorPage.toString());
                    LOG.info("TaskMonitorTaskService.sendTaskMonitorInfo sendEmail time={}", TimeUtils.getFormateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }

            }
            LOG.info("TaskMonitorTaskService.sendTaskMonitorInfo end time={}", TimeUtils.getFormateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            LOG.error("TaskMonitorTaskService.sendTaskMonitorInfo error exception={}", e);
        }
    }

    /**
     * 拼接邮件页面内容样式
     *
     * @param TaskMonitorRecords
     */
    private void taskMonitorEmailPage(List<TaskMonitorRecord> TaskMonitorRecords, List<String> taskNameList) {
        taskMonitorPage.append(Dvp.HTML_HEAD);
        taskMonitorPage.append("<body style=' height: auto;width:auto; padding: 0; margin: 0; border: 0; overflow: auto; font-size: 1px; font-family: 微软雅黑;'>");
        taskMonitorPage.append("<table <table  cellpadding='0' cellspacing='0'>");
        taskMonitorPage.append("<table style='border-spacing: 0; width=100%; border-bottom: 0;font-size: 1vm; border-right: 0;table-layout: fixed;'  cellspacing='0'");
        taskMonitorPage.append("<tr><td style='font-size:1.5vw;text-align:center;valign:center;border-right:none' colspan='27'>");
        taskMonitorPage.append("定时任务监控告警");
        taskMonitorPage.append("</td></tr>");
        taskMonitorPage.append("<tr>");
        for (String head : heads) {
            taskMonitorPage.append("<th style='font-family:微软雅黑;" +
                    "font-size:1.3vw;" +
                    "border-right-width: 1px;border-right-style: solid;border-right-color: #C1DAD7;" +
                    "border-bottom-width: 1px;border-bottom-style: solid;border-bottom-color:#C1DAD7;" +
                    "border-top-width: 1px;border-top-style: solid;border-top-color:#C1DAD7;" +
                    "letter-spacing: 1px;text-transform: uppercase;" +
                    "text-align:center;" +
                    " background-color: #CAE8EA;'>");
            taskMonitorPage.append(head);
            taskMonitorPage.append("</th>");

        }
        Boolean flat = true;
        for (TaskMonitorRecord TaskMonitorRecord : TaskMonitorRecords) {
            taskNameList.remove(TaskMonitorRecord.getTaskName());
            if (TaskMonitorRecord.getIsSuccess() == 1 && TaskMonitorRecord.getCompleteTime().getTime() -
                    TaskMonitorRecord.getStartTime().getTime() <= FIVEHOUR) {
                continue;
            }
            flat = false;
            taskMonitorPage.append("</tr><tr>");
            addTaskMonitorRecordTd(TaskMonitorRecord.getTaskName(), false);
            addTaskMonitorRecordTd(TaskMonitorRecord.getIp(), false);
            addTaskMonitorRecordTd(TaskMonitorRecord.getPartnerId(), false);
            if (TaskMonitorRecord.getIsSuccess() == 0) {
                if (TaskMonitorRecord.getStartTime() != null && TaskMonitorRecord.getExceptionTime() == null) {
                    addTaskMonitorRecordTd("定时任务还在运行中", true);

                } else {
                    addTaskMonitorRecordTd(TaskMonitorRecord.getFailureCause(), true);

                }

            } else {
                addTaskMonitorRecordTd("定时任务已运行完成，但是运行时间超过5小时", true);

            }
            addTaskMonitorRecordTd(TimeUtils.getFormateTimeNotNull(TaskMonitorRecord.getStartTime(), "yyyy-MM-dd HH:mm:ss"), false);
            if (TaskMonitorRecord.getIsSuccess() == 0) {
                addTaskMonitorRecordTd(TimeUtils.getFormateTimeNotNull(TaskMonitorRecord.getExceptionTime(), "yyyy-MM-dd HH:mm:ss"), false);
                addTaskMonitorRecordTd("", false);
            } else {
                addTaskMonitorRecordTd("", false);
                addTaskMonitorRecordTd(TimeUtils.getFormateTimeNotNull(TaskMonitorRecord.getCompleteTime(), "yyyy-MM-dd HH:mm:ss"), false);
            }
        }

        for (String s : taskNameList) {
            flat = false;
            taskMonitorPage.append("</tr><tr>");
            addTaskMonitorRecordTd(s, false);
            addTaskMonitorRecordTd("", false);
            addTaskMonitorRecordTd("", false);
            addTaskMonitorRecordTd("定时任务尚未运行", true);
            addTaskMonitorRecordTd("", false);
            addTaskMonitorRecordTd("", false);
            addTaskMonitorRecordTd("", false);

        }
        taskMonitorPage.append("</tr>");
        taskMonitorPage.append("</table></div><div style='width:300px;margin:auto;text-align:center'></table>");
        taskMonitorPage.append("</body></html>");
        if (flat) {
            taskMonitorPage.setLength(0);
        }

    }

    private void addTaskMonitorRecordTd(String tdString, Boolean flat) {
        String largeWidth = "";
        if (flat) {
            largeWidth = "width:50%;";
        }
        taskMonitorPage.append("<td style='border-right-width: 1px;border-right-style: solid;border-right-color:" +
                "#C1DAD7;border-bottom-width: 1px;border-bottom-style: solid;border-bottom-color: #C1DAD7;text-align:" +
                "center;font-size:1.2vw;color: #4f6b72;border-left-width: 1px;border-left-style: solid;border-left-color:" +
                " #C1DAD7;word-wrap:break-word;");
        taskMonitorPage.append(largeWidth + "'>");
        taskMonitorPage.append(tdString);
        taskMonitorPage.append("</td>");

    }


}
